<?php

//<meta http-equiv="refresh" content="5" >

//defined( '_VALID_MOS' ) or die( 'Restricted access' );

//if ( $_GET["eventid"] == "" )
//	exit;

define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) . "/../t2" );
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();

$mainframe->route();
$user =& JFactory::getUser();


/*
try {
	$eventid=intval($_GET["eventid"]);
}
catch (Exception $e ) 
{
	exit;
}

*/
$eventid=2;

require "jumi_dbconfig.php";

$this_username = $user->username;
$this_useremail = $user->email;
$this_userid = $user->id;
$this_usertype = $user->usertype;


function SendCommandSF($command,$para1,$para2 ) {
    switch ($command)
    {
	case "POST":
		return PostComment(urldecode($para1),$para2);	
		break;
	case "UP":
		return Vote("UP",$para1);	
		break;
	case "DOWN":
		return Vote("DOWN",$para1);	
		break;
	case "HIDE":
		return Admin("HIDE",$para1);	
		break;
	case "RELOADTOP":
		return ReloadTopComments();	
		break;
	case "RELOADALL":
		return ReloadAllComments();	
		break;


    }
    return "OK";
}

function Admin($mode, $commentid)
{
	global $this_username;
	global $this_userid;
	global $eventid;
	global $db;
	if ($this_username =="" )
	{
		return "NOTLOGIN";
	}
	switch ( $mode )
	{
		case "HIDE":
			$published=0;
			break;
		case "SHOW":
			$published=1;
			break;
	} 
	
	$query = sprintf("update comment set published=%d where id=%d or parentid=%d ",
		$published,$commentid,$commentid);
	try  {
		$result = mysql_query("$query",$db) ;
	}
 	catch (Exception $e)
	{
		return "ADMINFAILED:$commentid";
	}
	return "ADMINOK:$commentid";
}

function ReloadTopComments()
{
	global $this_username;
	global $this_userid;
	global $eventid;
	global $db;
	$query = "SELECT a.id,a.userid,username,comment,date_format(datecreated,'%Y-%m-%d %H:%i') as date1,ifnull(sum( b.up_vote),0)as up_vote,ifnull(sum( b.down_vote),0)as down_vote FROM comment a left join comment_vote b on a.id=b.commentid where eventid = '$eventid' and published=1 group by a.id order by ifnull(sum(b.up_vote),0)-ifnull(sum(b.down_vote),0) desc,a.id desc limit 0,3";

	$result = mysql_query($query,$db) or die (" died on query: ". $query); 
	$count=0;
//	$top= array();
  	$top="<table width=\"400\" border=0><tr><td colspan=\"5\"><h1><font cace=\"Helvetica\" color=\"#666666\">Top comments and questions: </font></h1></td></tr>\n";
	while ($myrow = mysql_fetch_array($result))
	{
		$comment_comment= stripslashes($myrow["comment"]);
		$comment_id = stripslashes($myrow["id"]);
		$comment_parentid = stripslashes($myrow["parentid"]);
		$comment_userid = stripslashes($myrow["userid"]);
		$comment_username = stripslashes($myrow["username"]);
		$comment_datecreated = stripslashes($myrow["date1"]);
		$comment_up= stripslashes($myrow["up_vote"]);
		$comment_down= stripslashes($myrow["down_vote"]);
	
		if ( $count %2 == 0 )
			$bgcolor="#EEEEEE";
		else
			$bgcolor="#efefef";
		$count++;
 		$str="<tr><td valign=\"top\"><table bgcolor=\"#ffffff\" border=0 width=\"400\">";


	        if ( $this_userid !="" )
	        {
	                $str.="<tr><td><table width=\"60\"><tr><td><a href='Javascript:VoteUp( $comment_id ) ' ><img src=\"/scripts/images/voteup.png\" border=\"0\"></a></td><td><font color=\"#939393\" size=\"+3\"><b>$comment_up</font></b></td></tr><tr><td> <a href='Javascript:VoteDown( $comment_id) ' ><img src=\"/scripts/images/votedown.png\" border=\"0\"></a></td><td><font color=\"#939393\" size=\"+3\"><b>$comment_down</font></b></td></tr></table></td><td>

	                $comment_comment</b><br><font size=\"-2\"><i>$comment_username</i>&nbsp; $comment_datecreated</font>
	                ";
	        }
	        else
	        {
	                $str.="<tr><td width=\"80\"><iframe src=\"http://therealnews.com/scripts/log2vote1.php\" width=\"95\" height=\"95\" frameborder=\"0\" scrolling=\"no\"></iframe></td><td></td><td>

	                $comment_comment</b><br><font size=\"-2\"><i>$comment_username</i>&nbsp; $comment_datecreated</font>
	                ";
	        }
		$str .="</table></td></tr><tr><td height=10></td></tr><tr><td ><hr class='dots'></td></tr>";
		//$top[] = $str;
		$top .=$str;
	}
	$top.="</table>\n";
	
	$str_result=json_encode($top); // save top result to a array, then encode it;
	return "RELOADTOPOK:$str_result";
}

function ReloadAllComments()
{
	global $this_username;
	global $this_userid;
	global $this_usertype;
	global $eventid;
	global $db;
	$query = "SELECT a.id,parentid,a.userid,username,comment,date_format(datecreated,'%Y-%m-%d %H:%i') as date1,ifnull(sum( b.up_vote),0)as up_vote,ifnull(sum( b.down_vote),0)as down_vote FROM comment a left join comment_vote b on a.id=b.commentid where eventid = '$eventid' and published=1 group by a.id order by ifnull(parentid,a.id) desc,a.id limit 0,100";
	$result = mysql_query($query,$db) or die (" died on query: ". $query);
	
	
	$curr_post=0;
	$all="<table width=300 border=0><tr><td><h1><font cace=\"Helvetica\" color=\"#666666\">Latest comments and questions: </font></h1></td></tr>";
	
	while ($myrow = mysql_fetch_array($result))
	{
	
		$comment_comment= stripslashes($myrow["comment"]);
		$comment_id = stripslashes($myrow["id"]);
		$comment_parentid = stripslashes($myrow["parentid"]);
		$comment_userid = stripslashes($myrow["userid"]);
		$comment_username = stripslashes($myrow["username"]);
		$comment_datecreated = stripslashes($myrow["date1"]);
		$comment_up= stripslashes($myrow["up_vote"]);
		$comment_down= stripslashes($myrow["down_vote"]);
	
		$str="";
	
		if ( $comment_parentid =="" ) //first post 
		{
			if ( $curr_post >0 )
			{
				$str .="<tr><td height=10></td></tr>";
			}
			$divpad="<div>";
			$curr_post=$comment_id;
		}
		else
			$divpad="<div style=\"padding:0px 0px 0px 60px;\">";
	    
	  	$str .="<tr><td>$divpad<table bgcolor=\"#ffffff\" border=0 width=\"400\" >";
	    
	
		if ( $this_userid !="" )
		{
			$str .="<tr><td><table width=\"60\"><tr><td ><a href='Javascript:VoteUp( $comment_id ) ' ><img src=\"/scripts/images/voteup.png\" border=\"0\"></a></td><td><font color=\"#939393\" size=\"+3\"><b>$comment_up</font></b></td></tr><tr><td> <a href='Javascript:VoteDown( $comment_id) ' ><img src=\"/scripts/images/votedown.png\" border=\"0\"></a></td><td><font color=\"#939393\" size=\"+3\"><b>$comment_down</font></b></td></tr></table></td><td>

	                $comment_comment</b><br><font size=\"-2\"><i>$comment_username</i>&nbsp; $comment_datecreated</font> ";
		}
		else
		{
			$str .="<tr><td width=\"40\"><tr><td width=\"80\"><iframe src=\"http://therealnews.com/scripts/log2vote1.php\" width=\"95\" height=\"95\" frameborder=\"0\" scrolling=\"no\"></iframe></td><td></td><td></td><td width=\"360\">
			
			$comment_comment</b><br><font size=\"-2\"><i>$comment_username</i>&nbsp; $comment_datecreated</font> ";
		}
	
		if ( $comment_parentid =="" && $this_userid!="" )
		{
			$str .="<a href='Javascript:ShowReply( $comment_id) ' >reply</a> ";
		}
		if ( $this_usertype == "Administrator" ||  $this_usertype == "Super Administrator" )
		{
			$str .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
			$str .= "<a href='Javascript:Hide( $comment_id) ' >delete</a> ";
			$str .= "<tr><td colspan='5' ><hr class='dots'></td></tr>";
		}
	
		if ( $this_userid !="" )
			$str .= "<div id=divreply_" . $comment_id . "></div><div id=mymessage_" . $comment_id . "></div></td></tr>";
	  
	  	$str .="</div></table></td></tr>";
		$all .=$str;
	}
	$all .="</table>";
	$str_result=json_encode($all); // save top result to a array, then encode it;
	return "RELOADALLOK:$str_result";
}

function Vote($mode, $commentid)
{
	global $this_username;
	global $this_userid;
	global $eventid;
	global $db;
	if ($this_username =="" )
	{
		return "NOTLOGIN";
	}
	switch ( $mode )
	{
		case "UP":
			$up=1;
			$down=0;
			break;
		case "DOWN":
			$up=0;
			$down=1;
	} 
	
	$query= "delete from comment_vote where commentid=$commentid and userid=$this_userid ";
	$result = mysql_query("$query",$db) ;
	$query = sprintf("INSERT INTO comment_vote (commentid,userid,up_vote,down_vote) VALUES ('%d','%d','%d','%d')",
		$commentid,$this_userid,$up,$down );
	try  {
		$result = mysql_query("$query",$db) ;
	}
 	catch (Exception $e)
	{
		return "VOTEFAILED:$commentid";
	}
	return "VOTEOK:$commentid";
}
function PostComment($comment,$commentid)
{
	global $this_username;
	global $this_userid;
	global $eventid;
	global $db;
	if ($this_username =="" )
	{
		return "NOTLOGIN";
	}
	if ( $commentid<=0) //	first post
	{
		$query = sprintf("INSERT INTO comment (eventid,userid,username,comment) VALUES ('%d','%d','%s','%s')",
			mysql_real_escape_string($eventid),
			mysql_real_escape_string($this_userid),
			mysql_real_escape_string($this_username),
			mysql_real_escape_string($comment) );
	}
	else // reply
	{
		$query = sprintf("INSERT INTO comment (eventid,parentid,userid,username,comment) VALUES (%d,%d,%d,'%s','%s')",
			mysql_real_escape_string($eventid),
			mysql_real_escape_string($commentid),
			mysql_real_escape_string($this_userid),
			mysql_real_escape_string($this_username),
			mysql_real_escape_string($comment) );
	}
	try  {
		$result = mysql_query("$query",$db) or die ("Error in query: $query. " . mysql_error());
	}
 	catch (Exception $e)
	{
		return "FAILED";
	}
	return "OK";
}


    require("sajax/sajax.php");
//    $sajax_debug_mode = true;

    $sajax_failure_redirect = "http://sajax.info/sajaxfail.html";
    sajax_export("SendCommandSF");
    sajax_handle_client_request();


?>
<html>
<head>
<link rel=StyleSheet href="criticizethis.css" type="text/css">

</head>
<body>
<style type="text/css">
<!--
body,td,th {
	font-family: Arial, Helvetica, sans-serif;
}
a:link {
	color: #06C;
}
-->
</style>
<script type="text/javascript" src="sajax/json2.stringify.js"></script>
<script type="text/javascript" src="sajax/json_stringify.js"></script>
<script type="text/javascript" src="sajax/json_parse_state.js"></script>
<script type="text/javascript" src="sajax/sajax.js"></script>


<script>

<?
	sajax_show_javascript();
?>
function FIND(item) {
   if( window.mmIsOpera ) return(document.getElementById(item));
   if (document.all) return(document.all[item]);
   if (document.getElementById) return(document.getElementById(item));
   return(false);
};

function SendCommand_callback( result) {
	
        if ( result == "NOTLOGIN" )
        {
		mymessage.innerHTML="<a target=_top href='/t2/index.php?option=com_user&view=login&return=<?=$redirectUrl?>'><strong>Login</strong></a> first to comment";
        }
        if ( result == "OK" )
        {
		mycomment.value="";
		mymessage.innerHTML="Comment submitted";
		//window.location.reload();
		ReloadAllComments();
		ReloadTopComments();
        }
        if ( result.indexOf("VOTEOK:")== 0 )
        {
		start=result.indexOf (":")+1;
		commentid=result.substr(start,result.length-start );
		obj=FIND("mymessage_" + commentid );
		//alert(commentid);
		obj.innerHTML="Vote OK. ";
		//window.location.reload();
		ReloadAllComments();
		ReloadTopComments();
	}
        if ( result.indexOf("VOTEFAILED:")== 0 )
        {
		start=result.indexOf (":")+1;
		commentid=result.substr(start,result.length-start );
		obj=FIND("mymessage_" + commentid );
		obj.innerHTML="Vote failed. You can't vote twice on same comment.";
	}
        if ( result.indexOf("ADMINOK:")== 0 )
        {
		start=result.indexOf (":")+1;
		commentid=result.substr(start,result.length-start );
		obj=FIND("mymessage_" + commentid );
		//alert(commentid);
		obj.innerHTML="Comment hidden. ";
		//window.location.reload();
		ReloadAllComments();
		ReloadTopComments();
	}
        if ( result.indexOf("RELOADTOPOK:")== 0 )
	{
		start=result.indexOf (":")+1;
		str1=result.substr(start,result.length-start );
		str= JSON.parse(str1);
		//alert(str);
		top_comments.innerHTML=str;
	}
        if ( result.indexOf("RELOADALLOK:")== 0 )
	{
		start=result.indexOf (":")+1;
		str1=result.substr(start,result.length-start );
		str= JSON.parse(str1);
		//alert(str);
		all_comments.innerHTML=str;
	}
}

function SendCommand(command, para1,para2)
{
        x_SendCommandSF(command, para1,para2, SendCommand_callback);
}
function VoteUp( commentid)
{
	SendCommand("UP",commentid,"");
}
function ReloadTopComments( )
{
	SendCommand("RELOADTOP","","");
	setTimeout('ReloadTopComments()', 30000);
}
function ReloadAllComments( )
{
	SendCommand("RELOADALL","","");
}
function sleep(milliSeconds){
    var startTime = new Date().getTime(); // get the current time
    while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}


function VoteDown( commentid)
{
	SendCommand("DOWN",commentid,"");
}
function ShowReply( commentid)
{
	div=FIND("divreply_"+commentid);
	div.innerHTML="<br>Reply comment: <br><textarea id=ta_reply"+ commentid + " cols=90 rows=3></textarea><br><input type=button onclick='javascript:HideReplyWindow("+ commentid +")' value=Cancel><input type=button onclick='javascript:ReplyComment("+ commentid + ")' value=Post>";
}

function HideReplyWindow( commentid)
{
	div=FIND("divreply_"+commentid);
	div.innerHTML="";

}

function Hide( commentid)
{
	SendCommand("HIDE",commentid,"");
}


function ReplyComment(commentid)
{
	obj=FIND("ta_reply" + commentid);
	msg=FIND("mymessage_" + commentid);
	if ( obj.value =="" )
	{
		msg.innerHTML="please type in a reply, then submit.";
		return;
	}
	if ( obj.value.length >1000  )
	{
		msg.innerHTML="Comment too long.";
		return;
	}
	SendCommand("POST",encodeURI(obj.value),commentid );
}

function PostComment()
{
	if ( mycomment.value =="" )
	{
		mymessage.innerHTML="please type in a comment, then submit.";
		return;
	}
	if ( mycomment.value.length >1000  )
	{
		mymessage.innerHTML="Comment too long.";
		return;
	}
	SendCommand("POST",encodeURI (mycomment.value) ,0 );
}

</script>

<table width="860"><tr><td valign="top">


<?
	if ( $this_username != "" ) {
?>

<font color="#5d5d5d" face="Helvetica"><b>Post question: (Maxium 1000 characters)</b></font><br><img src="http://therealnews.com/scripts/collapsedivs/images/social.gif"><br>


<textarea id=mycomment cols=70 rows=5 name=mycomment></textarea><br>
<input type=image src="http://nocache.therealnews.com/scripts/collapsedivs/images/submit_orange.gif" align="left" onclick='javascript:PostComment()' value=Post><div id=mymessage></div></div>
<?
	} else
	{
	
		//$redirectUrl = base64_encode($_SERVER['REQUEST_URI'] );
		$redirectUrl = base64_encode( "/t2/component/content/545?task=view" );
		//echo "<!-- uri: ". $_SERVER['REQUEST_URI']  ."//-->";

		echo " <h3><font color=\"#666666\">Please <a href=\"http://login.therealnews.com/t2/index.php?option=com_user&view=login&return=$redirectUrl\" target=\"_top\">login</a> first to write a comment or question.</font></h3>";
	}

?>




    
    
    </td><td valign="top">
<div id=top_comments></div>
    
  <br>
  <?
if ( $this_username == "" )
{
$redirectUrl = base64_encode("/web4/debate_show.php" );


?>

  <?
}
else
{
?>

<?


echo "user: $this_usertype<br>";
}
?>
    
<div id=all_comments>
</td></tr></table>
<script>
sleep(2000);
ReloadTopComments();
ReloadAllComments();

</script>
</body>
</html>
